package com.charger.trade.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.charger.PromoteOperations.domain.Client;
import com.charger.PromoteOperations.domain.ClientNewclient;
import com.charger.PromoteOperations.domain.Invite;
import com.charger.PromoteOperations.domain.Newclient;
import com.charger.PromoteOperations.service.ClientNewclientService;
import com.charger.PromoteOperations.service.IClientService;
import com.charger.PromoteOperations.service.IInviteService;
import com.charger.PromoteOperations.service.NewclientService;
import com.charger.PromoteOperations.util.IntegralCalculator;
import com.charger.charger.domain.Charger;
import com.charger.charger.service.IChargerService;
import com.charger.chargingStation.domain.Chargingstation;
import com.charger.chargingStation.service.IChargingstationService;
import com.charger.transactionflow.domain.Transactionflow;
import com.charger.transactionflow.service.ITransactionflowService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.charger.common.annotation.Log;
import com.charger.common.core.controller.BaseController;
import com.charger.common.core.domain.AjaxResult;
import com.charger.common.enums.BusinessType;
import com.charger.trade.domain.Chargingrecords;
import com.charger.trade.service.IChargingrecordsService;
import com.charger.common.utils.poi.ExcelUtil;
import com.charger.common.core.page.TableDataInfo;


/**
 * 交易管理Controller
 * 
 * @author ruoyi
 * @date 2024-11-22
 */
@RestController
@RequestMapping("/trade/trade")
public class ChargingrecordsController extends BaseController
{
    @Autowired
    private IChargingrecordsService chargingrecordsService;
    @Autowired
    private IClientService clientService;

    @Autowired
    private IChargingstationService chargingstationService;

    @Autowired
    private IChargerService chargerService;

    @Autowired
    private NewclientService newclientService;

    @Autowired
    private ClientNewclientService clientNewclientService;

    @Autowired
    private ITransactionflowService transactionflowService;

    @Autowired
    private IInviteService inviteService;

    /**
     * 查询交易管理列表
     */
    @PreAuthorize("@ss.hasPermi('trade:trade:list')")
    @GetMapping("/list")
    public TableDataInfo list(Chargingrecords chargingrecords) {
        startPage();
        List<Chargingrecords> list = chargingrecordsService.selectChargingrecordsList(chargingrecords);

        for (Chargingrecords aa:list){
            System.out.println(aa.getClientId());
            Client client = clientService.selectClientById(aa.getClientId());
            aa.setClient(client);
        }
        for (Chargingrecords aa:list){
            System.out.println(aa.getChargingstationsId());
            Chargingstation chargingstation = chargingstationService.selectChargingstationByChargingstationId(aa.getChargingstationsId());
            aa.setChargingstation(chargingstation);
        }
        for (Chargingrecords aa:list){
            System.out.println(aa.getChargerId());
            Charger charger = chargerService.selectChargerByChargerId(aa.getChargerId());
            aa.setCharger(charger);
        }
        return getDataTable(list);
    }

    /**
     * 导出交易管理列表
     */
    @PreAuthorize("@ss.hasPermi('trade:trade:export')")
    @Log(title = "交易管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Chargingrecords chargingrecords)
    {
        List<Chargingrecords> list = chargingrecordsService.selectChargingrecordsList(chargingrecords);
        ExcelUtil<Chargingrecords> util = new ExcelUtil<Chargingrecords>(Chargingrecords.class);
        util.exportExcel(response, list, "交易管理数据");
    }

    /**
     * 获取交易管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('trade:trade:query')")
    @GetMapping(value = "/{chargingrecordsId}")
    public AjaxResult getInfo(@PathVariable("chargingrecordsId") Long chargingrecordsId)
    {
        return success(chargingrecordsService.selectChargingrecordsByChargingrecordsId(chargingrecordsId));
    }

    /**
     * 新增交易管理
     */
    @PreAuthorize("@ss.hasPermi('trade:trade:add')")
    @Log(title = "交易管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Chargingrecords chargingrecords)
    {
//        获得新增记录对应客户积分
        Long clientId = chargingrecords.getClientId();
        Client client = clientService.selectClientById(clientId);
        Long integral = client.getIntegral();
//        通过积分调用积分工具类获得本次消费折扣
        Double discount = IntegralCalculator.integralDiscount(integral);
//        获得本次记录中消费金额，得到折扣后的金额
        String expenses = chargingrecords.getExpenses();
        Double discountExpenses = Double.valueOf(expenses) * discount;
//        将折扣后的金额设置为该对象的消费金额
        chargingrecords.setExpenses(String.valueOf(discountExpenses));
//        调用积分工具类，传入本次消费金额，获得对应的积分
        Long newIntegral = IntegralCalculator.moneyIntegral(Long.valueOf(expenses));
//        修改客户积分
        client.setIntegral(integral + newIntegral);
        clientService.updateClient(client);
        System.out.println("折扣后金额："+chargingrecords.getExpenses());
        System.out.println("本次消费积分："+newIntegral);
//        通过客户姓名等信息，调用新用户查询方法，查询其新用户id
        String name = client.getName();
        QueryWrapper<Newclient> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        Newclient newclient = newclientService.getOne(wrapper);
        if (newclient != null){
            Long id = newclient.getId();
//        通过新用户id，调用客户新用户中间表查询方法，查询出该新用户id对应的记录
            QueryWrapper<ClientNewclient> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("newclient_id", id);
            ClientNewclient byId = clientNewclientService.getOne(wrapper1);
//        从该记录获取与老客户的好友关系以及是否为新用户以及邀请人id
            Long oldClientId = byId.getClientId();
//        将积分添加到该新用户所对应的老客户（邀请人）列表中
            Client client1 = clientService.selectClientById(oldClientId);
            Long integral1 = client1.getIntegral();
            client1.setIntegral(integral1/2 + newIntegral);
            clientService.updateClient(client1);
            System.out.println("老客户的积分："+client1.getIntegral());
            //        将本次充电老客户获得的积分修正到邀请管理表中
            Invite invite = inviteService.selectInviteByClientId(oldClientId);
            invite.setInviteMoney(String.valueOf(newIntegral));
            inviteService.updateInvite(invite);
        }
        int i = chargingrecordsService.insertChargingrecords(chargingrecords);
//        将本次充电记录插入交易流水表中
//        1.获取本次充电记录中的信息
//        充电记录id，客户id，充电站id
        Long chargingrecordsId = chargingrecords.getChargingrecordsId();
        Long clientId1 = chargingrecords.getClientId();
        Long chargingstationsId = chargingrecords.getChargingstationsId();
//        2.创建一个交易流水对象，将本次充电记录中的信息赋给该对象
        Transactionflow transactionflow = new Transactionflow();
        transactionflow.setChargingrecordsId(chargingrecordsId);
        transactionflow.setClientId(clientId1);
        transactionflow.setChargingstationId(chargingstationsId);
//        3.调用交易流水插入方法
        transactionflowService.insertTransactionflow(transactionflow);
        System.out.println("交易流水插入成功");


        return toAjax(i);
    }

    /**
     * 修改交易管理
     */
    @PreAuthorize("@ss.hasPermi('trade:trade:edit')")
    @Log(title = "交易管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Chargingrecords chargingrecords)
    {
        return toAjax(chargingrecordsService.updateChargingrecords(chargingrecords));
    }

    /**
     * 删除交易管理
     */
    @PreAuthorize("@ss.hasPermi('trade:trade:remove')")
    @Log(title = "交易管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{chargingrecordsIds}")
    public AjaxResult remove(@PathVariable Long[] chargingrecordsIds)
    {
        return toAjax(chargingrecordsService.deleteChargingrecordsByChargingrecordsIds(chargingrecordsIds));
    }
}
